<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/6 0006
 * Time: 17:04
 */
namespace app\modules\content\controllers;

use app\libs\Pager;
use app\modules\content\models\HotActive;
use yii;
use app\libs\ApiControl;
use app\libs\GetData;

class HotActiveController extends ApiControl
{
    public $enableCsrfValidation = false;

    /**
     * [actionIndex 热门活动列表]
     * @Author don
     * @Date   2021-12-15
     * @return [type]     [description]
     */
    public function actionIndex()
    {
        // 从数据库获取数据
        $page = Yii::$app->request->get('page',1);
         $cate = Yii::$app->request->get('cate');
        $where = ' where 1=1';
         if ($cate != false) {
             $where .= " and cate=$cate";
         }

        $offset = 15 * ($page - 1);
        $count = Yii::$app->db->createCommand("select count(*) as count from {{%hot_active}} $where")->queryOne();
        $data = Yii::$app->db->createCommand("select * from {{%hot_active}} $where order by id desc limit $offset,15")->queryAll();
        $url = "/content/hot-active/index?cate=$cate&page";
        $count = $count['count'];
        $page = new Pager("$url", $count, $page, 15);
        $str = $page->GetPager();
        return $this->render('index', ['data' => $data,'str'=>$str]);
    }

    /**
     * [actionAdd 添加]
     * @Author don
     * @Date   2021-12-15
     * @return [type]     [description]
     */
    public function actionAdd()
    {
        if (!$_POST) {
            // 判断是修改还是添加$id
            $id = Yii::$app->request->get('id', '');
            if (empty($id)) {
                return $this->render('add');
            } else {
                $data = Yii::$app->db->createCommand("select * from {{%hot_active}} where id=" . $id)->queryOne();
                return $this->render('add', ['data' => $data]);
            }
        } else {
            // f_d($_POST);
            $getdata = new GetData();
            $must = array('title' => '活动名称');
            $data = $getdata->PostData($must, 'hot_active');
            if (empty($data['id'])) {
                $re = Yii::$app->db->createCommand()->insert("{{%hot_active}}", $data)->execute();
            } else {
                $model = new HotActive();
                $re = $model->updateAll($data, 'id=:id', array(':id' => $data['id']));
            }
            if ($re) {
                $this->redirect('index');
            } else {
                echo '<script>alert("数据添加\修改失败，请重试");history.go(-1);</script>';
                die;
            }
        }
    }

    /**
     * [actionDel 删除]
     * @Author don
     * @Date   2021-12-15
     * @return [type]     [description]
     */
    public function actionDel()
    {
        $id = Yii::$app->request->get('id', '');
        $re = HotActive::deleteAll("id=:id", array(':id' => $id));
        if ($re) {
            echo true;
        }
    }

}